我们来观察以下四段代码的区别:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| const p1 = new Promise(function (resolve, reject) { setTimeout(function () { throw new Error("test"); }, 0); }); p1.catch(function (error) { console.log("Catch1: ", error); });
const p2 = new Promise(function (resolve, reject) { setTimeout(function () { reject(new Error("test")); }, 0); }); p2.catch(function (error) { console.log("Catch2: ", error); });
const p3 = new Promise(function (resolve, reject) { throw new Error("test"); }); p3.catch(function (error) { console.log("Catch3: ", error); });
const p4 = new Promise(function (resolve, reject) { reject(new Error("test")); }); p4.catch(function (error) { console.log("Catch4: ", error); });
|
then
和catch
返回新的Promise
对象,finally
返回本身。
all
的then
,catch
的调用优先级低于all
的元素本身的then
,catch
。
以下两者代码的区别:(定义 Promise 的时候会执行其中的代码)
1 2 3 4 5 6 7 8 9 10 11
| const f = () => console.log("now"); Promise.resolve().then(f); console.log("next");
const f = () => console.log("now"); (() => new Promise((resolve) => resolve(f())))(); console.log("next");
|